import { ref, Ref } from 'vue';
import type { Cell, Column } from '../types';

export function useEditManager(emit: Function) {
  const isEditing = ref(false);
  const editingCell = ref({ row: -1, col: -1 });
  const editInputValue = ref('');
  const clickTimer = ref<number | null>(null);
  const CLICK_DELAY = 200;

  const enterEditMode = (
    rowIndex: number,
    colIndex: number,
    selectedCells: Ref<Set<string>>,
    clearSelection: (selectedCells: Set<string>) => void,
    isEditingRef: Ref<boolean>,
    editingCellRef: Ref<{ row: number; col: number }>,
    tableData: Ref<Cell[][]>,
    editInputValueRef: Ref<string>
  ) => {
    // 清除已存在的定时器
    if (clickTimer.value) {
      clearTimeout(clickTimer.value);
      clickTimer.value = null;
    }

    // 清除当前选中
    clearSelection(selectedCells.value);

    // 设置编辑状态
    isEditingRef.value = true;
    editingCellRef.value = { row: rowIndex, col: colIndex };
    editInputValueRef.value = tableData.value[rowIndex][colIndex].name;
  };

  const finishEditing = (
    isEditingRef: Ref<boolean>,
    editingCellRef: Ref<{ row: number; col: number }>,
    editInputValueRef: Ref<string>,
    tableData: Ref<Cell[][]>,
    saveState: () => void
  ) => {
    if (isEditingRef.value) {
      const { row, col } = editingCellRef.value;
      if (tableData.value[row] && tableData.value[row][col]) {
        const oldValue = tableData.value[row][col].name;
        const newValue = editInputValueRef.value;
        // 只有值发生变化时才保存
        if (oldValue !== newValue) {
          tableData.value[row][col].name = newValue;
          saveState();
          emit('update:changeUnit', { row, col, oldValue, newValue });
        }
      }
      isEditingRef.value = false;
      editingCellRef.value = { row: -1, col: -1 };
    }
  };
  const cancelEditing = (isEditingRef: Ref<boolean>, editingCellRef: Ref<{ row: number; col: number }>) => {
    isEditingRef.value = false;
    editingCellRef.value = { row: -1, col: -1 };
  };
  return {
    isEditing,
    editingCell,
    editInputValue,
    clickTimer,
    CLICK_DELAY,
    enterEditMode,
    finishEditing,
    cancelEditing
  };
}
